<template>
  <div class="login_container">
    <div class="login_box">
      <!--logo-->
      <div class="login-logo">
        <img src="../assets/img/img.png" alt="">
      </div>
      <!-- 表单-->
      <el-form :model="loginForm" :rules="rules" class="login_from" ref="loginForm">
        <!--   account-->
        <el-form-item prop="account">
          <el-input prefix-icon="el-icon-s-custom" v-model="loginForm.account" autofocus></el-input>
        </el-form-item>
        <!-- psw -->
        <el-form-item prop="psw">
          <el-input prefix-icon="el-icon-key" v-model="loginForm.psw" type="password"
                    @keyup.enter.native="login"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="success" @click="register" size="small" round>注册</el-button>
          &nbsp;&nbsp;&nbsp;
          <el-radio v-model="loginForm.type" label="2">用户</el-radio>
          <el-radio v-model="loginForm.type" label="1">管理员</el-radio>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="danger" @click="reset('loginForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 注册-->
    <el-dialog title="用户注册" :visible.sync="dialogVisible" width="40%">
      <!--表单-->
      <el-form :model="registerForm" status-icon :rules="registerRules" ref="registerForm" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="账号" prop="account">
          <el-input v-model="registerForm.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="registerForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="psw">
          <el-input type="password" v-model="registerForm.psw" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPsw">
          <el-input v-model="registerForm.checkPsw" type="password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <!--底部-->
      <span slot="footer" class="dialog-footer">
         <el-button native-type="reset" @click="reset('registerForm')">重 置</el-button>
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="sendRegister">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>

import axios from "axios";

export default {
  name: 'Login',
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.psw) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    const checkLength = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('该选项不能为空'));
      } else if (value.trim().length < 3 || value.trim().length > 7) {
        callback(new Error("长度不能小于3或大于7且不能有空格"));
      } else {
        callback();
      }
    };

    return {
      loginForm: {
        account: "",
        psw: "",
        type: "1",
      },
      registerForm: {
        account: "",
        name: "",
        phone: "",
        psw: "",
        checkPsw: "",
      },
      dialogVisible: false,
      registerRules: {
        account: [
          {required: true, validator: checkLength, trigger: 'blur'},
        ],
        psw: [
          {required: true, validator: checkLength, trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
        ],
        checkPsw: [
          {validator: validatePass2, trigger: 'blur', required: true},
        ],
        phone: [
          {required: false, message: '请输入电话', trigger: 'blur'},
          {min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur'}
        ]
      },
      rules: {
        account: [
          {required: true, validator: checkLength, trigger: 'blur'},
        ],
        psw: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
        ],
      },
      url: "",
      path: "",
    }
  },
  methods: {
    reset(from) {
      if (from === "registerForm") {
        this.$refs.registerForm.resetFields();
        return;
      }
      if (from === "loginForm") {
        this.$refs.loginForm.resetFields();
      }
    },
    login() {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return;
        this.getType();
        this.$http({
          method: "post",
          changeOrigin: "true",
          url: this.url,
          data: {
            account: this.loginForm.account,
            psw: this.loginForm.psw,
          }
        }).then(result => {
          // 注意 通过axios获取的数据，都在result.data中放着
          if (result.data.code === 200) {
            sessionStorage.setItem("token", result.data.data.token);
            sessionStorage.setItem("name", result.data.data.name);
            sessionStorage.setItem("account", result.data.data.account);
            sessionStorage.setItem("type", result.data.data.type);
            this.$router.push(this.path);
            this.resetTypeMessage();
            return this.$message({
              showClose: true,
              message: '登陆成功',
              type: 'success'
            });
          }
          this.resetTypeMessage();
          return this.$message.error(result.data.msg)
        })
      })
    },
    register() {
      this.dialogVisible = true
    },
    sendRegister() {
      this.$refs.registerForm.validate(validate => {
        if (!validate) return;
        axios.post("/user/register", {
          account: this.registerForm.account.trim(),
          name: this.registerForm.name.trim(),
          psw: this.registerForm.psw.trim(),
          phone: this.registerForm.phone.trim(),
        }).then(res => {
          console.log(res.data.data)
          if (res.data.code === 200) {
            /* 跳转到用户页，并保存token */
            const data = res.data.data;
            sessionStorage.setItem("token", data.token);
            sessionStorage.setItem("account", this.registerForm.account);
            sessionStorage.setItem("name", this.registerForm.name);
            sessionStorage.setItem("type", false + "");
            this.$message.success("注册成功");
            this.$router.push('/userHome');
          } else if (res.data.code === 300) {
            this.$message.warning("此用户名已存在");
          }
        })
      })
    },
    getType() {
      if (parseInt(this.loginForm.type) === 1) {
        this.url = "/admin/login";
        this.path = "/home";
      } else {
        this.url = "/user/login";
        this.path = "/userHome";
      }
    },
    resetTypeMessage() {
      this.url = "";
      this.path = "";
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  background-image: url("../assets/img/bg.png");
  height: 100%;
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .login-logo {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eeeeee;
    }
  }

}

.btns {
  display: flex;
  justify-content: flex-end;
}

.login_from {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

</style>
